function [data,detectors,motors] = specread5(filename,nscan)
% SPECREAD5 read a spec data file
% function [data,counters] = specread5(filename,nscan)
% Reads scans from a SPEC file
% nscan = scan number
% counters = string containing the names of counters
% detectors = structure containing all counter names and their values
% motors = vector containing all motor positions
% Author: Keijo Hamalainen 30.03.98
% last modified (version 5) by Simo Huotari 10.04.2009

% Try to open mat file
try,
% disp('Trying to load MAT file.');
load(['/tmp_14_days/huotari/' filename '_' num2str(nscan) 'mat.mat']);
catch,
%  disp('Did not succeed! Will read the specfile.');
  
% First open the file, if error occurs exit the function
%  try,
%  disp('Trying to open MAJOR specfile');
%  load(['/tmp_14_days/huotari/' filename '_bigmat.mat']);
%  catch,
%    disp('Not ok, loading the slow text file');
    
[fid,msg] = fopen(filename,'r');
if fid == -1;
   error(msg);
end;

line=fgetl(fid);	% Reads the first line
while (isstr(line) & ~feof(fid));
    if length(line)>3;
        if line(1:2)=='#S';
            iscan=sscanf(line(3:length(line)),'%g'); 	% Scan number
            if (sum(iscan==nscan)>0 | nargin<2);    	% Correct scan
                data=[];				% Initialize data variable
		motors=[];
                line(1:2)='##';
                while (isstr(line) & ~strcmp(line(1:2),'#S'));% Empty or scan end
                    line=fgetl(fid);			  	% Read new line
                    line=[line '  '];			% Trick to accept empty line
                    if line(1:2)=='#L', counterss=line(3:end); end
		    if line(1:2)=='#P', motors=[motors str2num(line(5:end))]; end
                    [numdata,n]=sscanf(line,'%g');
                    if n > 4;
                        numdata=numdata';
                        try data=[data;numdata]; end% Read numbers 
                    end
                    if feof(fid);
                        break
                    end
                    
                end
            else
                line=fgetl(fid);  
            end
        else
            line=fgetl(fid);
        end
    else
        line=fgetl(fid);
    end
end
fclose(fid);

while counterss(1)==' '; counterss=counterss(2:end); end
while counterss(end)==' '; counterss=counterss(1:end-1); end
testfin=1;
while length(testfin)>0,
  testfin=findstr('    ',counterss);
  if length(testfin)>0, counterss=counterss([1:testfin-1,testfin+1:end]); end
end
testfin=1;
while length(testfin)>0,
  testfin=findstr('   ',counterss);
  if length(testfin)>0, counterss=counterss([1:testfin-1,testfin+1:end]); end
end

counterss=['  ' counterss '  '];
ncounters=findstr('  ',counterss);
detectors=struct('counternames',[]);
for ii=1:length(ncounters)-1,
  countername = deblank(counterss(ncounters(ii)+2:ncounters(ii+1)));
  countername(find(countername=='.'))=[];
  detectors.counternames{ii}=countername;
  iz=find(~isspace(countername));
  countername = countername(iz);
  s=['detectors.' lower(countername) '=data(:,ii);'];
  eval(s);
end
%disp('Saving the spec file to a MAT file');
%matfilename = ['/tmp_14_days/huotari/' filename '_' num2str(nscan) 'mat.mat'];
%save(matfilename,'data','detectors','motors','-v7.3');
end
%disp('Finished!');
